package com.inspur.cloud.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;


/**
 * Created by yuanfq on 2020-07-04.
 */
public class HttpUtils {

    public static String getServiceResult(String url, Map param,String serviceName) {
        final String CONTENT_TYPE_TEXT_JSON = "application/json;charset=UTF-8";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //String host= FrameConf.getValue("service."+serviceName);
        //HttpPost httPost =new HttpPost(host+url);
        HttpPost httPost =new HttpPost(url);
        Map<String, Object> map=new HashMap<>();
        String res="";
        try {
            StringEntity se = new StringEntity(JSONObject.toJSONString(param),"UTF-8");
            se.setContentType(CONTENT_TYPE_TEXT_JSON);
            httPost.setEntity(se);
            HttpResponse response = httpclient.execute(httPost);
            HttpEntity entity = response.getEntity();
            if (entity != null && entity.getContentLength() != 0) {
                res = EntityUtils.toString(entity, "UTF-8");
                System.out.println("Response content: " + res);
            } else System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public static Map getServiceResultMap(String url, Map param,String serviceName) {
        String jsonStr=getServiceResult(url, param,serviceName);
        Map<String, Object> dataMap =
                JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});
//    if("0".equals(dataMap.get("code").toString())){
        return (Map<String,Object>)dataMap.get("data");
//    }else return
    }

    public static List<Map<String,Object>> getServiceResultMapToList(String url, Map param,String serviceName) {
        String jsonStr=getServiceResult(url, param,serviceName);
        Map<String, Object> dataMap =
                JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});

        List<Map<String,Object>> dataList =
                JSON.parseObject(dataMap.get("data").toString(), new TypeReference<List<Map<String,Object>>>() {});

//    if("0".equals(dataMap.get("code").toString())){
        return dataList;
//    }else return
    }


    public static void responseJson(HttpServletResponse response, String jsonStr) throws IOException {
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonStr);
    }

    /**
     * 结果转为list
     * @param url
     * @param param
     * @param serviceName
     * @return
     */
    public static List<Map<String,Object>> getServiceResultList(String url,Map param,String serviceName){
        String jsonStr=getServiceResult(url, param,serviceName);
        List<Map<String,Object>> dataList =
                JSON.parseObject(jsonStr, new TypeReference<List<Map<String,Object>>>() {});
        return dataList;
    }

    public static Map conversionServiceResulttoMap(String url, Map param,String serviceName) {
        String jsonStr=getServiceResult(url, param,serviceName);
        Map<String, Object> dataMap =
                JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});
//    if("0".equals(dataMap.get("code").toString())){
        return dataMap;
//    }else return
    }
    public static void responseJson(HttpServletResponse response, Object object) throws IOException{
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSONObject.toJSONString(object));
    }

    public static void response(HttpServletResponse response, String str) throws IOException{
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(str);
    }

    public static String doPost(String url, Map <String, Object> params, String charset) throws IOException{
        StringBuffer response = new StringBuffer();
        HttpClient client = new HttpClient() {};
        PostMethod method = new PostMethod(completeUrl(url));
        method.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        method.setRequestBody(JSON.toJSONString(params));
        InputStream responseBodyStream = null;
        InputStreamReader streamReader = null;
        BufferedReader reader = null;
        try{
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK || method.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR){
                responseBodyStream = method.getResponseBodyAsStream();
                streamReader = new InputStreamReader(responseBodyStream, charset);
                reader = new BufferedReader(streamReader);
                String line;
                while ((line = reader.readLine()) != null){
                    response.append(line);
                }
            }
        }
        catch (IOException e){
            System.out.println("执行com.inspur.common.utils.HttpUtil.java HTTP Post请求" + url + "时，发生异常！");
            e.printStackTrace();
        }
        finally{
            try{
                responseBodyStream.close();
                streamReader.close();
                reader.close();
            }
            catch (IOException e){
                System.out.println(
                        "执行com.inspur.common.utils.HttpUtil.java HTTP Post请求" + url + "时，发生异常，关闭流异常！");
                e.printStackTrace();
            }
            method.releaseConnection();
        }
        return response.toString();
    }


    public static String doPut(String url, Map <String, Object> params, String charset) throws IOException{
        StringBuffer response = new StringBuffer();
        HttpClient client = new HttpClient() {};
        PutMethod method = new PutMethod(completeUrl(url));
        method.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        method.setRequestBody(JSON.toJSONString(params));
        InputStream responseBodyStream = null;
        InputStreamReader streamReader = null;
        BufferedReader reader = null;
        try{
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK || method.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR){
                responseBodyStream = method.getResponseBodyAsStream();
                streamReader = new InputStreamReader(responseBodyStream, charset);
                reader = new BufferedReader(streamReader);
                String line;
                while ((line = reader.readLine()) != null){
                    response.append(line);
                }
            }
        }
        catch (IOException e){
            System.out.println("执行com.inspur.common.utils.HttpUtil.java HTTP Put请求" + url + "时，发生异常！");
            e.printStackTrace();
        }
        finally{
            try{
                responseBodyStream.close();
                streamReader.close();
                reader.close();
            }
            catch (IOException e){
                System.out.println(
                        "执行com.inspur.common.utils.HttpUtil.java HTTP Put请求" + url + "时，发生异常，关闭流异常！");
                e.printStackTrace();
            }
            method.releaseConnection();
        }
        return response.toString();
    }

    public static String doPostForm(String url,Map <String, Object> params)  throws IOException{
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Object eo : params.entrySet()) {
                Map.Entry<String, String> e = (Map.Entry<String, String>) eo;
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.substring(0, sb.length() - 1);
        }
        System.out.println("send_url:" + url);
        System.out.println("send_data:" + sb.toString());
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    public static String doPostJson(String url, Map <String, Object> params, String charset) throws IOException{
        String basicInfoJsonStr = JSON.toJSONString(params);

        //创建连接对象
        HttpClient httpClient = new HttpClient();
        //创建请求
        PostMethod method = new PostMethod(completeUrl(url));
        //设置请求头格式为json格式
        RequestEntity entity=new StringRequestEntity(basicInfoJsonStr,"application/json","UTF-8");
        //设置请求体信息
        method.setRequestEntity(entity);
        //创建连接
        try {
            httpClient.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream in = method.getResponseBodyAsStream();
        InputStreamReader isr = new InputStreamReader(in, "UTF-8");
        StringBuffer sb =  new StringBuffer();
        char[] b = new char[4096];
        for(int n; (n = isr.read(b)) != -1;) {
            sb.append(new String(b, 0, n));
        }
        return sb.toString();
    }

    public static String doGet(String url){
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(completeUrl(url));
        try{
            //getMethod.setRequestHeader("X-AUTH-TOKEN", accessToken);
            getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
            httpClient.executeMethod(getMethod);
        }
        catch (HttpException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        String userInfo = "";
        try{
            userInfo = getMethod.getResponseBodyAsString();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return userInfo;
    }


    public static String doDelete(String url){
        HttpClient httpClient = new HttpClient();
        DeleteMethod deleteMethod = new DeleteMethod(completeUrl(url));
        try{
            //getMethod.setRequestHeader("X-AUTH-TOKEN", accessToken);
            httpClient.executeMethod(deleteMethod);
        }
        catch (HttpException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        String returnInfo = "";
        try{
            returnInfo = deleteMethod.getResponseBodyAsString();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return returnInfo;
    }



    private static String completeUrl(String url) {
        if(!StringUtils.startsWithAny(url, new CharSequence[]{"http://", "https://"})) {
            url = "http://" + url;
        }
        return url;
    }
}
